package com.kanche.bigbaby.collection;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.kanche.bigbaby.BigBabyApplication;
import com.kanche.bigbaby.collection.domain.Vehicle;
import com.kanche.bigbaby.collection.domain.VehicleUploadPhase;
import com.squareup.otto.Bus;

import retrofit.RetrofitError;

public class VehicleUploadTaskService extends Service implements VehicleUploadTask.Callback {
    private static final String TAG = "ImageUploadTaskService";

    VehicleUploadTaskQueue queue;
    Bus bus;

    private boolean running;

//    private KKCheDBHelper dbHelper;

    @Override
    public void onCreate() {
        super.onCreate();

//        dbHelper = new KKCheDBHelper(this);
        BigBabyApplication application = ((BigBabyApplication) getApplication());
        bus = application.getBus();
        queue = application.getVehicleUploadTaskQueue();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
//        if (dbHelper != null) {
//            dbHelper.close();
//        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        executeNext();
        return START_STICKY;
    }

    private void executeNext() {
        if (running) return; // Only one task at a time.
        if (queue == null) return;
        VehicleUploadTask task = queue.peek();
        if (task != null) {
            running = true;
//            PreferencesUtils.lockVehicle(this, task.vehicleRowId());
            task.execute(this);
        } else {
            stopSelf(); // No more tasks are present. Stop.
        }
    }

    @Override
    public void onSuccess(final Vehicle vehicle, VehicleUploadPhase phase, long batchId) {
        if (phase == VehicleUploadPhase.UPLOAD_VEHICLE) {
            running = false;
            queue.remove();
//            dbHelper.removeVehicle(vehicle.get_id());
//            PreferencesUtils.unlockVehicle(this, vehicle.get_id());
            Guard.showMessage(this, "[" + vehicle.getSpec().getDisplayValue() + "]" + "上传成功");

            bus.post(new VehicleUploadSuccessEvent(vehicle, batchId));
            executeNext();
        } else {
//            dbHelper.updateVehicle(vehicle.get_id(), vehicle);
        }

    }

    @Override
    public void onProgress(Vehicle vehicle, VehicleUploadPhase phase, long batchId) {
        bus.post(new VehicleUploadProgressEvent(vehicle, phase, batchId));
    }

    @Override
    public void onFailure(RetrofitError error, Vehicle vehicle, VehicleUploadPhase phase, long batchId) {
        running = false;
        queue.remove();
//        PreferencesUtils.unlockVehicle(this, vehicle.get_id());
        bus.post(new VehicleUploadFailureEvent(error, vehicle, batchId));
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
